package com.cbtx.tablet.ui

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.TextUtils
import androidx.recyclerview.widget.LinearLayoutManager
import com.cbtx.tablet.App
import com.cbtx.tablet.R
import com.cbtx.tablet.adapter.ImageDetailAdapter
import com.cbtx.tablet.bean.GoodsItemBean
import com.cbtx.tablet.bean.ImageMore
import com.cbtx.tablet.constant.HttpConstant.DEVICE_WXQRCODE
import com.cbtx.utils.DeviceUtil
import com.cbtx.utils.zxing.ZxingUtils
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_goods_detail.*

class GoodsDetailActivity : AbsBaseActivity() {

    lateinit var authItem: GoodsItemBean
    private val mImageList: MutableList<String> = ArrayList()
    lateinit var mAdapter: ImageDetailAdapter

    override fun layoutId(): Int = R.layout.activity_goods_detail

    override fun initView(savedInstanceState: Bundle?) {
        mTvCode.text = "云屏编码: ${App.androidId}"
        mTvBack.setOnClickListener {
            finish()
        }

        mIvCover.setImageBitmap(getQrBitmap())

        authItem = intent.getSerializableExtra("authItem") as GoodsItemBean
        mImageList.clear()
        mImageList.addAll(getImageList())

        mTvTitle.text = if(authItem.goodsName == null) "" else authItem.goodsName
        mTvType.text =  "藏品类别：" + if(authItem.category == null)"" else authItem.category
        mTvYearName.text =  "藏品年代：" + if(authItem.years == null)"" else authItem.years
        mTvPrice.text = if(authItem.price == null) "" else "￥${authItem.price}"
        mTvDetail.text =  if(authItem.introduce == null) "" else authItem.introduce
        mTvDistrict.text = "规格：${authItem.specs?.replace("\n","")}"
        mTvBoWuGuang.text =  "市场价：￥${authItem.insurancePrice}"
        mAdapter = ImageDetailAdapter()
        mRvDetailImages.layoutManager = LinearLayoutManager(this)
        mRvDetailImages.adapter = mAdapter
        mAdapter.data = mImageList
    }

    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun getImageList(): MutableList<String> {
        val images = mutableListOf<String>()
        if (!TextUtils.isEmpty(authItem.img)) {
            val imageMore = Gson().fromJson(authItem.img, ImageMore::class.java)
            imageMore.more?.let { images.addAll(it) }
        }
        return images
    }

    private fun getQrBitmap(): Bitmap? {

        val color = resources.getColor(R.color.c_e0c28f)
        val bgColor = resources.getColor(R.color.c_f8f8f8)
        val logoBitmap =
            BitmapFactory.decodeResource(resources, R.mipmap.ic_logo_qr_code)
        val url = "${DEVICE_WXQRCODE}${DeviceUtil.getSerialNumber(this)}"

        return ZxingUtils.createQRCodeWithLogo(url, 148, logoBitmap, 0, color, bgColor)
    }
}